#!/usr/bin/python
###############################################################################
#Programmers:  Danil Dotsenko, dd@accentsolution.com                          #
#Date: 14/07/2006                                                             #
#Filename: installer.py                                                       #
#Version: 0.1.1                                                                 #
#                                                                             #
#                                                                             #
#       Copyleft 2006 Danil Dotsenko                                          #
#                                                                             #
#    This program is free software; you can redistribute it and/or modify     #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation; either version 2 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this program; if not, write to the Free Software              #
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA #
#                                                                             #
###############################################################################

import karamba
import os
from commands import getoutput
import re
import localconf # this is a custom wrapper for ConfigParser. Should be in local dir.
import zipfile
from installertasks import * # these functions that manage invidual installer tasks and is a part of Karambino package.

###########################################################################
# All applet settings go here, and are accessible from everywhere.
###########################################################################
class configuration:
	'''
	An all-encoupasing, application-wide configuration storage location. This is not a permanent file-based storage
	'''
	def __init__(self):
		self.name = "Karambino Installer"
		self.version = "0.1.1, December 30, 2006"
		self.author = "Danil (Suslik) Dotsenko (dd@accentsolution.com)"
		self.sourceskz = None
		self.widgetNum = None
		self.ini = None

###########################################################################
# This is how you make all configs available to you - now a global "variable" with methods.
###########################################################################
appConfig=configuration()

###########################################################################
# This will read the config file for settings
#
def getConfigs(widget):
	global appConfig

	#appConfig.sourceskz = 'plastikyakuake.zip'
	appConfig.widgetNum = widget
	appConfig.sourceskz = karamba.getThemePath(widget)
	if zipfile.is_zipfile(appConfig.sourceskz): # this means we are running from inside the skz.
		zip = zipfile.ZipFile(appConfig.sourceskz)
		configlist = zip.read('installer.ini').splitlines()
		maindata = zip.read('maindata.xml')
	else:
		# this means we are running from a folder.
		# Usually done while testing the installer rutine.
		# note, unzipping will not work as exected, so, create a dummy zip and hard-point to it for tests.
		filePtr = open('installer.ini','r')
		configlist = filePtr.readlines()
		filePtr.close()
		filePtr = open('maindata.xml','r')
		maindata = filePtr.readlines()
		filePtr.close()

	appConfig.ini = localconf.cfgObject(configlist)
	try:
		appConfig.ini.set('variables','%installername%',re.search('(?<=\<name\>).+(?=\</name\>)',maindata).group())
	except:
		appConfig.ini.set('variables','%installername%','installer')

#
##########################################################

###########################################################################
# This permanently closes theme with appName. We dont ask any questions.
# We close this applet in all running instances of SuperKaramba.
def closeApplet(appName):
	skname = getoutput('dcop | grep superkaramba')
	skname = skname.splitlines()
	for instance in skname:
		karamba.execute('dcop '+instance+' KarambaIface closeTheme "'+appName+'"')
#
###########################################################################

###########################################################################
# This goes through the config - this is the main code.

def processConfig():
	global appConfig

	cfg = appConfig.ini

	# 2 odd things 1st, Variables section and Instaler section

	# getting the dict type object with system variables
	installerVars = dict(cfg.get('variables'))
	# in addition to these, we also have built-in variables
	# %home% - user's home dir.
	# %sourceskz% - path name of skz file
	installerVars['%home%'] = os.getenv('HOME')
	installerVars['%sourceskz%'] = appConfig.sourceskz
	# reference to the config object used by script, not the installer.ini
	installerVars['%cfgObject%'] = localconf.cfgObject()
	# Well, we are done with Installer section. Lets start the actual process.
	section = cfg.get('installer','nextaction')

	# it's a 4-step process
	# - get actiontype
	# - for that actiontype get needed pieces of info
	# - do the action
	# - fetch next section name and rewind

	# tasks = installertasks.tasksObject()
	# def task(actiontype, settings, installerVars=None):

	while section != 'quit':
		actiontype = cfg.get(section, 'actiontype')
		settings = cfg.get(section) # this puts all settings in that section into a dictionary-type structure.
		output = task (actiontype, settings, installerVars)
		if output:
			installerVars = output
		section = cfg.get(section, 'nextaction')
		if section == '%output%':
			section = installerVars['%output%']
	# now we are at Quit section.
	closeApplet(installerVars['%installername%'])
#
###########################################################################

##################################################################
# KARAMBA's built-in functions
##################################################################

#this is called when you widget is initialized
def initWidget(widget):
	global appConfig
	# if isThisFirstTime(widget)==False:
	getConfigs(widget)
	processConfig()
	# putOldLocation(widget) # this puts the applet at its recorded location.
	# workingImg = karamba.getThemeImage(widget, "working")
	# karamba.deleteImage(widget,loadImg)

#this is called everytime your widget is updated
#the update inverval is specified in the .theme file
def widgetUpdated(widget):
	pass

# This will be printed when the widget loads.
print appConfig.name+" version "+appConfig.version+" is loaded"
